package by.dkusch.aircompany.webapp.page.users.panel;

import java.util.ArrayList;
import java.util.Set;

import javax.inject.Inject;

import org.apache.wicket.Page;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.PageCreator;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.CompoundPropertyModel;

import by.dkusch.aircompany.model.tables.UserGrant;
import by.dkusch.aircompany.model.tables.UserProfile;
import by.dkusch.aircompany.services.UserGrantService;
import by.dkusch.aircompany.services.UserService;
import by.dkusch.aircompany.webapp.page.base.common.GrantDataProvider;
import by.dkusch.aircompany.webapp.page.base.enums.ActionType;

public class GrantEditPanel extends Panel {

	private static final long serialVersionUID = 1L;
	@Inject
	private UserService userService;
	@Inject
	private UserGrantService grantService;

	private GrantDataProvider grantDataProvider;

	public GrantEditPanel(String id, final UserProfile profile, final PageCreator pageCreator, ActionType action) {
		super(id);

		grantDataProvider = new GrantDataProvider(profile);

		profile.setUserGrant(userService.getGrants(profile));
		final Form<Set<UserGrant>> form = new Form<Set<UserGrant>>("grantForm", new CompoundPropertyModel<Set<UserGrant>>(profile.getUserGrant()));

		DataView<UserGrant> dataView = new DataView<UserGrant>("grantList", grantDataProvider) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(Item<UserGrant> item) {
				final UserGrant grant = item.getModelObject();
				item.add(new GrantRowPanel("grant-row-panel", grant));
			}

		};

		form.add(dataView);
		final SubmitLink submitLink = new SubmitLink("sumbit-link") {

			private static final long serialVersionUID = 1L;

			@Override
			public void onSubmit() {
				super.onSubmit();
				grantService.saveList(new ArrayList<UserGrant>(profile.getUserGrant()));
				Page page = pageCreator.createPage();
				page.info(getString("column.common.action.saved"));
				setResponsePage(page);
			}

		};
		submitLink.setOutputMarkupId(true);
		form.add(submitLink);

		add(new Link<Void>("back-link") {

			private static final long serialVersionUID = 1L;

			@Override
			public void onClick() {
				setResponsePage(pageCreator.createPage());
			}

		});
		add(form);
	}

	@Override
	protected void onInitialize() {
		super.onInitialize();

	}

}
